package com.spring.aicloud.controller;

import com.alibaba.cloud.ai.tongyi.chat.TongYiChatClient;
import com.alibaba.cloud.ai.tongyi.image.TongYiImagesClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spring.aicloud.entity.Answer;
import com.spring.aicloud.entity.enums.AiModelEnum;
import com.spring.aicloud.entity.enums.AiTypeEnum;
import com.spring.aicloud.service.IAnswerService;
import com.spring.aicloud.util.AppVariable;
import com.spring.aicloud.util.MinIoUtil;
import com.spring.aicloud.util.ResponseEntity;
import com.spring.aicloud.util.SecurityUtil;
import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.image.Image;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/tongyi")
public class TongyiController {

    @Resource
    private TongYiChatClient chatClient;
    @Resource
    private TongYiImagesClient imagesClient;
    @Resource
    private IAnswerService answerService;
    @Resource
    private MinIoUtil minIoUtil;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 聊天
     *
     * @param question
     * @return
     */
    @PostMapping("/chat")
    public ResponseEntity chat(String question) {
        if (!StringUtils.hasLength(question)) {
            return ResponseEntity.fail("问题不能为空");
        }
        // 执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.TONGYI.getValue(),
                AiTypeEnum.CHAT.getValue());
        String result = ""; // 大模型返回的结构
        boolean isSave = false; // 数据添加状态
        // 获取分布式锁实例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            // 获取分布式锁
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (!isLock) {
                // 获取分布式锁失败
                return ResponseEntity.fail("请勿频繁调用接口！");
            }
            result = chatClient.call(new Prompt(question))
                    .getResult()
                    .getOutput()
                    .getContent();
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(result);
            answer.setModel(AiModelEnum.TONGYI.getValue());
            answer.setUid(uid);
            answer.setType(AiTypeEnum.CHAT.getValue());
            isSave = answerService.save(answer);
            if (isSave) {
                // 如果保存成功，更新缓存
                int type = AiTypeEnum.CHAT.getValue();
                int model = AiModelEnum.TONGYI.getValue();
                String cacheKey = AppVariable.getListCacheKey(uid, model, type);
                List<Answer> cachedList = new ArrayList<>();
                Object cachedData = redisTemplate.opsForValue().get(cacheKey);
                if (cachedData != null) {
                    cachedList = (List<Answer>) cachedData;
                }
                cachedList.add(0,answer); // 将新回答添加到缓存列表中  // 0 表示在列表开头插入
                redisTemplate.opsForValue().set(cacheKey, cachedList, 1, TimeUnit.DAYS); // 更新缓存
            }
        } catch (Exception e) {
            e.printStackTrace(); // 记录异常信息
            return ResponseEntity.fail("系统繁忙，请稍后再试！");
        } finally {
            rLock.unlock();
        }
        return ResponseEntity.succ(result);
    }

    /**
     * 绘画
     *
     * @param question
     * @return
     */
    @PostMapping("/draw")
    public ResponseEntity draw(String question) {
        if (!StringUtils.hasLength(question)) {
            return ResponseEntity.fail("问题不能为空");
        }
        // 执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.TONGYI.getValue(),
                AiTypeEnum.DRAW.getValue());
        String url = ""; // 大模型返回的结构
        boolean isSave = false; // 数据添加状态
        // 获取分布式锁实例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            // 获取分布式锁
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (!isLock) {
                // 获取分布式锁失败
                return ResponseEntity.fail("请勿频繁调用接口！");
            }
            Image image = imagesClient.call(new ImagePrompt(question))
                    .getResult().getOutput();
            String base64 = image.getB64Json();



            try (InputStream inputStream = new ByteArrayInputStream(
                    Base64.getDecoder().decode(base64))) {
                String fileName = "ty-" + UUID.randomUUID().toString().replace("-", "");
                url = minIoUtil.upload(fileName,inputStream,"image/png");
            } catch (Exception e) {
                return ResponseEntity.fail("操作失败，请重试！");
            }
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(url);
            answer.setModel(AiModelEnum.TONGYI.getValue());
            answer.setUid(uid);
            answer.setType(AiTypeEnum.DRAW.getValue());
            isSave = answerService.save(answer);
            if (isSave) {
                // 如果保存成功，更新缓存
                int type = AiTypeEnum.DRAW.getValue();
                int model = AiModelEnum.TONGYI.getValue();
                String cacheKey = AppVariable.getListCacheKey(uid, model, type);
                List<Answer> cachedList = new ArrayList<>();
                Object cachedData = redisTemplate.opsForValue().get(cacheKey);
                if (cachedData != null) {
                    cachedList = (List<Answer>) cachedData;
                }
                cachedList.add(0,answer); // 将新回答添加到缓存列表中  // 0 表示在列表开头插入
                redisTemplate.opsForValue().set(cacheKey, cachedList, 1, TimeUnit.DAYS); // 更新缓存
            }
        } catch (Exception e) {
            e.printStackTrace(); // 记录异常信息
            return ResponseEntity.fail("系统繁忙，请稍后再试！");
        } finally {
            rLock.unlock();
        }
        return ResponseEntity.succ(url);
    }

    /**
     * 获取聊天列表
     */
    @PostMapping("/getchatlist")
    public ResponseEntity getChatList() {
        Long uid = SecurityUtil.getCurrentUser().getUid();
        int type = AiTypeEnum.CHAT.getValue();
        int model = AiModelEnum.TONGYI.getValue();
        String cacheKey = AppVariable.getListCacheKey(uid, model, type);
        Object list = redisTemplate.opsForValue().get(cacheKey);
        if (list == null) { // 缓存不存在
            QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid", uid);
            queryWrapper.eq("type", type);
            queryWrapper.eq("model", model);
            queryWrapper.orderByDesc("aid");
            List<Answer> dataList = answerService.list(queryWrapper);
            // 存储到缓存中
            redisTemplate.opsForValue().set(cacheKey, dataList, 1, TimeUnit.DAYS);
            return ResponseEntity.succ(dataList);
        } else {
            return ResponseEntity.succ(list);
        }
    }

    /**
     * 获取绘画历史列表
     */
    @PostMapping("/getdrawlist")
    public ResponseEntity getDrawList() {
        Long uid = SecurityUtil.getCurrentUser().getUid();
        int type = AiTypeEnum.DRAW.getValue();
        int model = AiModelEnum.TONGYI.getValue();
        String cacheKey = AppVariable.getListCacheKey(uid, model, type);
        Object list = redisTemplate.opsForValue().get(cacheKey);
        if (list == null) { // 缓存不存在
            QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid", uid);
            queryWrapper.eq("type", type);
            queryWrapper.eq("model", model);
            queryWrapper.orderByDesc("aid");
            List<Answer> dataList = answerService.list(queryWrapper);
            // 存储到缓存中
            redisTemplate.opsForValue().set(cacheKey, dataList, 1, TimeUnit.DAYS);
            return ResponseEntity.succ(dataList);
        } else {
            return ResponseEntity.succ(list);
        }
    }
}

